package yxy.game.pm2.command.plainsCraft;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PlainsCraftMessage;
import yxy.game.pm2.module.plainsCraft.RankPlainsCraft;
import yxy.game.pm2.module.player.PlayerHandle;

import java.util.Collection;

/** 中原争霸 中原争霸排行榜 */
@MessageType(proto = Command.PlainsCraftRank, classtype = PlainsCraftMessage.PlainsCraftRankRequest.class)
public class CMD_PlainsCraftRank extends Command<PlainsCraftMessage.PlainsCraftRankRequest> {

	@Override
	public void execute(MessageSource messageSource, PlainsCraftMessage.PlainsCraftRankRequest request) {
		String playerCode = messageSource.getTag();
		int level = request.getLevel();

		PlainsCraftMessage.PlainsCraftRankResponse.Builder response = PlainsCraftMessage.PlainsCraftRankResponse.newBuilder();

		if (level < 1 || level > 5) {
			send(messageSource, response, Result.ParamError);
			return;
		}

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		RankPlainsCraft rankPlainsCraft = new RankPlainsCraft(areaBean.getGroupId(), level);
		try {
			PlayerHandle playerHandle = new PlayerHandle();
			Collection<RankEntry> top = rankPlainsCraft.top(rankPlainsCraft.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();

				PlainsCraftMessage.PlainsCraftRank.Builder builder = PlainsCraftMessage.PlainsCraftRank.newBuilder();

				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				response.addRank(builder);
			}
			{
				int playerRank = 0;
				RankEntry entry = rankPlainsCraft.get(playerCode);
				if (entry != null) {
					playerRank = rankPlainsCraft.rank(playerCode);
				}

				PlainsCraftMessage.PlainsCraftRank.Builder builder = PlainsCraftMessage.PlainsCraftRank.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				response.setMy(builder);
			}
			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, PlainsCraftMessage.PlainsCraftRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}